package com.lanou.bookstore.user.web.servlet;

import com.lanou.bookstore.user.domain.User;
import com.lanou.bookstore.user.service.LoginService;
import com.lanou.bookstore.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;


// url后加.action 是为了和jsp或者其他静态页面做区分
//一看见这个路径,就知道它访问的是个servlet
@WebServlet(name = "LoginServlet", urlPatterns = "/login.do")
public class LoginServlet extends HttpServlet {
    private LoginService loginService = new LoginService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        password = MD5Util.MD5WithSalt(password);

        User user = loginService.login(username, password);

        if (user == null) {
            // 登录失败
            fieldMsg(request, response, "用户名/密码错误,点击返回登录页面");
        } else {
            // 登录成功
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            response.sendRedirect("/index.jsp");
        }

    }

    private void fieldMsg(HttpServletRequest request, HttpServletResponse response, String msg) throws ServletException, IOException {
        // String msg = "用户名/密码错误,点击返回登录页面";
        String path = "/jsps/user/login.jsp";
        request.setAttribute("msg", msg);
        request.setAttribute("path", path);
        response.setStatus(302);
        response.setHeader("Refresh", "5;URL=/jsps/user/login.jsp");
        request.getRequestDispatcher("/jsps/msg.jsp")
                .forward(request, response);
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect("/jsps/top.jsp");
    }
}
